package com.nuoniu.sibanyun.service.production.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nuoniu.sibanyun.common.exception.NuoNiuException;
import com.nuoniu.sibanyun.common.lang.StringUtils;
import com.nuoniu.sibanyun.entity.production.ErpBomDetail;
import com.nuoniu.sibanyun.entity.production.ErpBomMain;
import com.nuoniu.sibanyun.mapper.production.VBomMainMapper;
import com.nuoniu.sibanyun.mapper.production.VProductionWorkDetailMapper;
import com.nuoniu.sibanyun.service.erp.IErpAccountService;
import com.nuoniu.sibanyun.service.production.IVBomDetailService;
import com.nuoniu.sibanyun.service.production.IVBomMainService;
import com.nuoniu.sibanyun.service.production.IVProductionWorkDetailService;
import com.nuoniu.sibanyun.service.production.IVProductionWorkMainService;
import com.nuoniu.sibanyun.userThread.UserInfo;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 小啊刚
 * @since 2021-01-08
 */
@Service
public class VBomMainServiceImpl extends ServiceImpl<VBomMainMapper, ErpBomMain> implements IVBomMainService {

    @Autowired
    private IVBomDetailService bomDetailService;
    @Autowired
    private IErpAccountService accountService;
    @Autowired
    private VProductionWorkDetailMapper workDetailMapper;

    @Override
    public Page<ErpBomMain> getList(Page page, ErpBomMain bomMain) {
        UserInfo userInfo = UserThreadLocal.get();
        QueryWrapper<ErpBomMain> queryWrapper = new QueryWrapper();
        queryWrapper.eq("company_id", userInfo.getCompanyId());
        if(bomMain.getInventoryId() != null) {
            queryWrapper.eq("inventory_id", bomMain.getInventoryId());
        }
        if(StringUtils.isNotBlank(bomMain.getSearchKey())) {
            queryWrapper.and(wrapper -> wrapper.likeRight("inventory_code", bomMain.getSearchKey()).or().like("inventory_name", bomMain.getSearchKey()));
        }
        return page(page, queryWrapper);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Long saveBom(ErpBomMain bomMain) {
        ErpBomMain bom = baseMapper.getBomByVersion(bomMain.getInventoryId(), bomMain.getVersionCode());
        UserInfo userInfo = UserThreadLocal.get();
        if(bom != null && (bomMain.getId() == null || !bom.getId().equals(bomMain.getId()))) {
            throw new NuoNiuException("版本号已存在");
        }
        //校验 是否 选择工艺路线
        Integer processRouteId = bomMain.getProcessRouteId();
        if( null == processRouteId)throw new NuoNiuException("请选择工艺路上");
        if(bomMain.getId() == null) {
            bomMain.setCompanyId(userInfo.getCompanyId());
            bomMain.setAccountId(accountService.getCurrentAccountId());
            bomMain.setCreateUserId(userInfo.getUserId());
            bomMain.setCreateUserName(userInfo.getRealName());
        }else {
            bomMain.setUpdateDate(LocalDateTime.now());
            bomMain.setUpdateUserId(userInfo.getUserId());
            bomMain.setUpdateUserName(userInfo.getRealName());
//            Integer count  = workDetailMapper.getCountByBom(bomMain.getId());
//            if(count > 0) {
//                throw new NuoNiuException("已使用，不能修改！");
//            }
        }

        //检查子级bom是否有父件
        bomMain.getOrderDetailList().forEach(b -> {
            b.setBaseQuantity(b.getRequireQuantity());
            if(null == b.getBaseUnit()){
                b.setBaseUnit(b.getUnitId());
            }
            if(StringUtils.isBlank(b.getBaseUnitName())){
                b.setBaseUnitName(b.getUnitName());
            }
//            if (null == b.getBaseQuantity() || b.getBaseQuantity().compareTo(BigDecimal.ZERO) == 0){
//
//            }
            if(b.getInventoryId().equals(bomMain.getInventoryId())) {
                throw new NuoNiuException("母件不能作为子件");
            }
            if(b.getBomId() != null) {
                checkBom(b.getBomId().longValue(), bomMain.getInventoryId());
            }
        });

        bomMain.setInventorySpecification(bomMain.getSpecification());
        Boolean result = this.saveOrUpdate(bomMain);
        if(result) {
            List<Long> detailIds = new ArrayList<>();
            List<ErpBomDetail> orderDetailList = bomMain.getOrderDetailList();
            orderDetailList.forEach(p -> {
                p.setOrderId(bomMain.getId().intValue());
                if(p.getId() != null) {
                    detailIds.add(p.getId());
                }
            });

            //删除明细
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("order_id", bomMain.getId());
            if(detailIds != null && detailIds.size() > 0) {
                wrapper.notIn("id", detailIds);
                bomDetailService.remove(wrapper);
            }else {
                bomDetailService.remove(wrapper);
            }
            //保存单据明细表
            bomDetailService.saveOrUpdateBatch(orderDetailList);
        }
        return bomMain.getId();
    }

    @Override
    public List<ErpBomDetail> getChildBomList(Long bomId) {
        return bomDetailService.getByBomId(bomId);
    }

    @Override
    public void examine(Long id, Integer status) {
        UserInfo userInfo = UserThreadLocal.get();
        //1.校验
        if (null == id || null == status || status > 1 || status < 0)throw new NuoNiuException("参数错误");
        //2.查询
        ErpBomMain erpBomMain = getById(id);
        if (null == erpBomMain || !userInfo.getCompanyId().equals(erpBomMain.getCompanyId()))throw new NuoNiuException("参数错误,请选择正确的记录");
        //3.  查询使用情况
//        if (0 == status){
//            Integer count  = workDetailMapper.getCountByBom(id);
//            if(count > 0) {
//                throw new NuoNiuException("已使用，不能弃审！");
//            }
//        }
        ErpBomMain bomMain = new ErpBomMain();
        bomMain.setVoucherState(status);
        bomMain.setId(id);
        bomMain.setReviewerDate(LocalDateTime.now());
        bomMain.setReviewerUserId(userInfo.getUserId());
        bomMain.setReviewerUserName(userInfo.getRealName());
        updateById(bomMain);
    }

    @Override
    @Transactional
    public void deleteById(Long id) {
        Integer count  = workDetailMapper.getCountByBom(id);
        if(count > 0) {
            throw new NuoNiuException("已使用，不能删除！");
        }

        QueryWrapper<ErpBomDetail> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id", id);
        bomDetailService.remove(wrapper);
        this.removeById(id);
    }


    public void checkBom(Long bomId, Integer inventoryId) {
        List<ErpBomDetail> bomDetails = bomDetailService.getByBomId(bomId);
        bomDetails.forEach(b -> {
//            System.out.println("正在检查bom明细id=" + b.getId() + "子bomId=" + (b.getBomId() != null ? b.getBomId() : ""));
            if(b.getInventoryId().equals(inventoryId)) {
                throw new NuoNiuException("母件不能作为子件");
            }else {
                if(b.getBomId() != null) {
                    checkBom(b.getBomId().longValue(), inventoryId);
                }
            }
        });
    }

    public void checkBomMaxLevel(Long bomId, Map<String, Map<String, String>> data) {

    }
}
